define([ "config", "jquery", "store",
	'angular',
	"jquery.cookie",
	"static/js/lib/md5"], function(config,$,store) {
	var app = angular.module("app",[]);

	app.controller('mainController', ["$q", "$scope", "$http", "$timeout", function($q, $scope, $http, $timeout) {
		$scope.currentSessionId = $.cookie("JSESSIONID");

		$scope.loginName = $.cookie("_TEMP_LOGIN_USER");
		$scope.$watch("loginName",function(a,b){
			if(a&&a!=b){
				$.cookie("_TEMP_LOGIN_USER", a, { expires: 0.01, path: window.location.href });
			}
		});
		$scope.initKeyProcess = function(){
			angular.element("#loginName").focus(function(){
				angular.element("#loginName").keyup(function ($event) {
					if($event.keyCode==13){
						angular.element("#password").focus();
					}
				})
			});
			angular.element("#password").focus(function(){
				angular.element("#password").keyup(function ($event) {
					if($event.keyCode==13){
						$scope.doLogin();
					}
				})
			});
			angular.element("#loginName,#password").blur(function(){
				angular.element("#loginName,#password").unbind("keyup");
			});
			angular.element("#loginName").focus();
		};
		$scope.initKeyProcess();

		$scope.doLogin = function(){
			$.ajax({
				type:'post',
				dataType:'json',
				url: config.ajaxUrlBase + "checkLogin/validateUserToken/"+ $scope.loginName +"/" + faultylabs.MD5($scope.password),
				success: function(response){
					if(response.code==1){
						$.cookie("BOSS_USER_INFO", JSON.stringify(response.data), { expires: 1, path: "/" });
						$.cookie("JSESSIONID", response.data.JSESSIONID);
						window.JSESSIONID = $.cookie("JSESSIONID");
						$timeout(function(){
							$scope.initPermissions();
						},0);
						window.location.href='index.html';
					}else{
						angular.element("#errorMsg").text(response.message);
					}
				}
			});
		};

		$scope.initPermissions = function(){
			var params = {
				//callback:'JSON_CALLBACK',
				JSESSIONID:JSESSIONID
			};
			var expire = store.get("permissionExpire");
			var permis = store.get("permissionStore");
			var cookie = JSESSIONID;
			if(!expire||!permis||expire!=cookie){
				$.ajax({
					url:config.ajaxUrlBase + "permission/getRights",
					data:params,
					dataType:"jsonp",
					success:function(response){
						if(response.code==1){
							store.set("permissionStore",response.data);
							store.set("permissionExpire",cookie);
						}else{
							store.remove("permissionStore");
							store.remove("permissionExpire");
						}
					},
					error:function(){
						store.remove("permissionStore");
						store.remove("permissionExpire");
					}
				});
			}
		};
	}]);

	angular.bootstrap(document, [ "app" ]);
});
